package com.D5Power.Editor
{
	import com.D5Power.Editor.EditorWindow.MapAttr;
	import com.D5Power.map.WorldMap;
	import com.adobe.images.PNGEncoder;
	
	import flash.display.BitmapData;
	import flash.events.Event;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.geom.Matrix;
	import flash.utils.ByteArray;
	
	import mx.controls.Alert;
	import mx.controls.MenuBar;
	
	import org.aswing.JMenu;
	import org.aswing.JMenuBar;
	import org.aswing.JMenuItem;
	import org.aswing.JPanel;
	import org.aswing.JWindow;
	import org.aswing.KeySequence;
	import org.aswing.KeyStroke;
	import org.aswing.event.AWEvent;

	public class D5Menu extends JPanel
	{
		
		private var bar:JMenuBar;
		private var _root:MapEditor
		
		/**
		 * 用于存储和外界有交互的对象
		 * 目前已知存储内容
		 * 0			视图菜单中的隐藏、显示网格
		 * 1			视图菜单中的显示、隐藏透明改变碰撞监测区
		 */ 
		private var hudong:Array;
		/**
		 * 现在正在打开的地图文件名
		 */ 
		private var _now_file:String='';
		
		public function D5Menu(e:MapEditor)
		{
			super();
			
			_root = e;
			
			bar = new JMenuBar();
			hudong = new Array();
			
			/* ---- 文件 ---- */
			var bt_file:JMenu = new JMenu("文件(&F)");
			var item_new:JMenuItem = new JMenuItem('新建');
			var item_open:JMenuItem = new JMenuItem('打开');
			var item_save:JMenuItem = new JMenuItem('保存');
			var item_save_as:JMenuItem = new JMenuItem('另存为');
			var item_save_4server:JMenuItem = new JMenuItem('生成服务器地图配置');
			
			bt_file.append(item_new);
			bt_file.append(item_open);
			bt_file.append(item_save);
			bt_file.append(item_save_as);
			bt_file.append(item_save_4server);
			
			item_new.addActionListener(__onItemClick);
			item_open.addActionListener(__onItemClick);
			item_save.addActionListener(__onItemClick);
			item_save_as.addActionListener(__onItemClick);
			item_save_4server.addActionListener(__onItemClick);
			
			item_new.setAccelerator(new KeySequence(KeyStroke.VK_CONTROL,KeyStroke.VK_C));
			item_open.setAccelerator(new KeySequence(KeyStroke.VK_CONTROL,KeyStroke.VK_O));
			item_save.setAccelerator(new KeySequence(KeyStroke.VK_CONTROL,KeyStroke.VK_S));
			
			/* ---- 编辑 ---- */
			var bt_edit:JMenu = new JMenu("编辑(&E)");
			var item_clear_build:JMenuItem = new JMenuItem('清空建筑');
			var item_clear_npc:JMenuItem = new JMenuItem('清空NPC');
			var item_clear_rock:JMenuItem = new JMenuItem('清空路点');
			var item_map_prop:JMenuItem = new JMenuItem('查看地图属性');
			
			bt_edit.append(item_clear_build);
			bt_edit.append(item_clear_npc);
			bt_edit.append(item_clear_rock);
			bt_edit.append(item_map_prop);
			
			item_clear_build.addActionListener(__onItemClick);
			item_clear_npc.addActionListener(__onItemClick);
			item_clear_rock.addActionListener(__onItemClick);
			item_map_prop.addActionListener(__onItemClick);
			
			var bt_tool:JMenu = new JMenu('工具(&T)');
			var item_map_cut:JMenuItem = new JMenuItem('地图切割器');
			
			bt_tool.append(item_map_cut);
			
			item_map_cut.addActionListener(__onItemClick);
			
			/* ---- 视图 ---- */
			var bt_view:JMenu = new JMenu('视图(&V)');
			var item_showtile:JMenuItem = new JMenuItem('显示网格');
			hudong.push(item_showtile);
			var item_showover:JMenuItem = new JMenuItem('显示透明碰撞');
			hudong.push(item_showover);
			
			
			bt_view.append(item_showtile);
			bt_view.append(item_showover);
			
			item_showtile.addActionListener(__onItemClick);
			item_showover.addActionListener(__onItemClick);
			
			item_showtile.setAccelerator(new KeySequence(KeyStroke.VK_CONTROL,KeyStroke.VK_T));
			
			/* ---- 帮助 ---- */
			var bt_help:JMenu = new JMenu("帮助(&H)");
			var item_about:JMenuItem = new JMenuItem('关于');
			bt_help.append(item_about);
			
			item_about.addActionListener(__onItemClick);
			
			/* ---- 结束 ---- */
			//fscommand( "trapallkeys" , "true");

			
			bar.append(bt_file);
			bar.append(bt_edit);
			bar.append(bt_tool);
			bar.append(bt_view);
			bar.append(bt_help);

			
			append(bar);
		}
		
		/**
		 * 获取互动对象
		 * @param	id
		 * 0			视图菜单中的隐藏、显示网格
		 */ 
		public function HudongItem(id:uint):JMenuItem
		{
			return hudong[id];	
		}
		
		private function __onItemClick(e:AWEvent):void
		{
			var item:JMenuItem = e.currentTarget as JMenuItem;
			switch(item.getText())
			{
				case '显示网格':
				case '隐藏网格':
					updateShowTile();
					break;
				case '显示透明碰撞':
				case '隐藏透明碰撞':
					updateShowOver();
					break;
				case '新建':
					newMap();
					break;
				case '另存为':
					saveMap('');
					break;
				case '生成服务器地图配置':
					saveMap4Server();
					break;
				case '打开':
					openMap();
					break;
				case '保存':
					saveMap(filename);
					break;
				case '清空建筑':
					_root.Shower.removeAllObject('BLIST');
					break;
				case '清空NPC':
					_root.Shower.removeAllObject('NPCLIST');
					break;
				case '清空路点':
					_root.Shower.clearTile();
					break;
				case '查看地图属性':
					showMapProp();
					break;
				case '关于':
					_root.about();
					break;
				case '地图切割器':
					_root.cutMapTool();
					break;
				default:
					trace(item.getText());
					break;
			}
		}
		
		/**
		 * 地图属性
		 */ 
		public function showMapProp():void
		{
			_root.newOrEditMap(MapAttr.EDITMAP);
		}
		
		public function newMap():void
		{
			_now_file='';
			_root.newOrEditMap(MapAttr.NEWMAP);
		}
		
		public function openMap():void
		{
			var file_open:File = File.applicationDirectory.resolvePath('config');
			file_open.browseForOpen('打开地图配置文件');
			file_open.addEventListener(Event.SELECT,onOpen);
		}
		
		public function saveMap4Server():void
		{
			if(filename=='')
			{
				_root.msg('提示','您必须先保存当前正在编辑的地图，才能根据文件名生成后缀为“_server”的地图配置文件');
				return;
			}
			
			var file:File = new File(File.applicationDirectory.resolvePath('config/'+filename+'_server').nativePath);
			var fs:FileStream = new FileStream();
			fs.open(file,FileMode.WRITE);
			fs.writeBytes(_root.Shower.ServerConfig);
			fs.close();
			_root.msg('提示','保存地图配置文件成功！');
			
		}
		
		public function saveMap(filename:String=''):void
		{
			var file:File;
			if(filename=='')
			{
				file = File.applicationDirectory.resolvePath('config');
				file.browseForSave('将地图配置文件另存为');
				file.addEventListener(Event.SELECT,onSaveAs);
			}else{
				file = new File(File.applicationDirectory.resolvePath('config/'+filename).nativePath);
				
				onSaveAs(file);
			}
			
		}
		
		/**
		 * 地图文件另存为
		 */ 
		public function onSaveAs(e:*,data:String=''):void
		{
			// 若e含有target对象，则以target为file对象（另存为），否则直接将e取为file对象（保存）
			var file:File = e.hasOwnProperty('target') ? e.target as File : e as File;
			// 通过二进制数据进行压缩
			var ba:ByteArray = new ByteArray();
			ba.writeUTFBytes(data=='' ? _root.Shower.Configer : data);
			ba.compress();
			
			// 保存数据
			var fs:FileStream = new FileStream();
			fs.open(file,FileMode.WRITE);
			fs.writeBytes(ba,0,ba.bytesAvailable);
			fs.close();
			
			_now_file = file.name;
			
			if(_root.Shower!=null && _root.Shower.AlphaMap!=null)
			{
				var bytes:ByteArray = new ByteArray();
				bytes = PNGEncoder.encode(_root.Shower.AlphaMap);
				
				// 写入透明检测原图
				var f:File = new File(File.applicationDirectory.resolvePath('config/'+_now_file+'.png').nativePath);
				fs.open(f,FileMode.WRITE);
				fs.writeBytes(bytes,0,ba.bytesAvailable);
				fs.close();
				
				// 写入透明检测缩略图（实际检测用图）
				var w:uint = int(Global.MAPSIZE.x/WorldMap.tileWidth);
				var h:uint = int(Global.MAPSIZE.y/WorldMap.tileHeight);
				var check:BitmapData = new BitmapData(w,h,true,0x00000000);
				check.draw(_root.Shower.AlphaMap,new Matrix(w/Global.MAPSIZE.x,0,0,w/Global.MAPSIZE.x),null,null,null,true);
				bytes = PNGEncoder.encode(check);
				f = new File(File.applicationDirectory.resolvePath('asset/AlphaMap/'+_now_file+'.png').nativePath);
				fs.open(f,FileMode.WRITE);
				fs.writeBytes(bytes,0,ba.bytesAvailable);
				fs.close();
				
				bytes.clear();
				check.dispose();
				bytes=null;
				check=null;
			}
		}
		
		/**
		 * 打开地图文件
		 */ 
		private function onOpen(e:Event):void
		{
			// 重置地图
			var file:File = e.target as File;
			
			_now_file = file.name;
			
			_root.startMap(_now_file);
		}
		
		public function updateShowTile():void
		{
			var item:JMenuItem = hudong[0];
			switch(item.getText())
			{
				case '显示网格':
				_root.Shower.showTile=true;
				item.setText("隐藏网格");
				break;
				case '隐藏网格':
				_root.Shower.showTile=false;
				item.setText("显示网格");
				break;
			}
		}
		
		public function updateShowOver():void
		{
			var item:JMenuItem = hudong[1];
			switch(item.getText())
			{
				case '显示透明碰撞':
				_root.Shower.showOver=true;
				item.setText("隐藏透明碰撞");
				break;
				case '隐藏透明碰撞':
				_root.Shower.showOver=false;
				item.setText("显示透明碰撞");
				break;
			}
		}
		
		/**
		 * 当前正在编辑的文件名
		 */ 
		public function get filename():String
		{
			return _now_file;
		}
	}
}